package com.terry.handler;

import java.nio.charset.Charset;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;

import com.terry.client.NettyClient;
import com.terry.interfaces.Contant;
import com.terry.utils.DateUtils;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.util.ReferenceCountUtil;
/**
 * @author pengpanting
 * 浏览器请求处理起，然后向target发送socket请求
 */
public class HttpServerHandler extends ChannelInboundHandlerAdapter {

	private StringBuffer requestHeader = new StringBuffer(); //转发的请求line－header
	private List<ByteBuf> reponseBodyList = new LinkedList<ByteBuf>();

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		try {
			if(msg instanceof HttpRequest) {
				HttpRequest reuqest = (HttpRequest)msg;
				if(HttpHeaders.isContentLengthSet(reuqest)) {
					long length1 = HttpHeaders.getContentLength(reuqest);
				}
				String reuqestLine = reuqest.method() + " " + reuqest.uri() + " " + reuqest.protocolVersion();
				requestHeader.append(reuqestLine).append("\r\n");
				HttpHeaders header = reuqest.headers();
				Iterator<Entry<String, String>> kk = header.iteratorAsString();
				while(kk.hasNext()) {
					Entry<String, String> item = kk.next();
					String headerString = item.getKey() + ": " + item.getValue();
					requestHeader.append(headerString).append("\r\n");
				}
				requestHeader.append("\r\n");
				System.out.println("rquestHeader(请求头部): " + DateUtils.formatDate(new Date()) +"\n" + requestHeader.toString());
			}
			if(msg instanceof HttpContent) {
				HttpContent content = (HttpContent)msg;
				ByteBuf bb = content.content();
				System.out.println("rquestBody(请求body): " + DateUtils.formatDate(new Date()) +"\n" + bb.toString(Charset.forName("UTF-8")));
				reponseBodyList.add(bb.copy());
			}
		} catch(Exception e) {
			e.printStackTrace();
		} finally {
			ReferenceCountUtil.release(msg);
		}
	}
	
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		String request = requestHeader.toString();
		if("".equals(request)) {
			ctx.close();
			return;
		}
		try {
			request = request.replace(Contant.SERVER_PORT+"", Contant.TARGET_PORT+"");
			request = request.replace(Contant.SERVER_HOST, Contant.TARGET_HOST);
			NettyClient client = new NettyClient(Contant.TARGET_HOST, Contant.TARGET_PORT);
			reponseBodyList.add(0, Unpooled.wrappedBuffer(request.getBytes("UTF-8")));
			client.run(ctx,reponseBodyList);
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}

	
}
